
exports.GAPurchaseSyncHandler = Core.Class.singleton ({

	synchPendingTransactions: function(callback) {
		this._awardCurrency = callback;
		// Get pending transactions and process them.
		var myself = this;
		Bank.Debit.getPendingTransactions(
			function(error, transactionIds) {
				if (error){
					var errorCode = error.errorCode;
					var errorDesc = error.description;
					console.log('Could not retrieve pending transactions. error: ' +errorCode + ', ' + errorDesc);
				}
				else if (transactionIds && (transactionIds.length >= 1)) {
					//console.log("TOTAL PENDING TXNS: " + transactionIds.length);
					myself._processOneTransaction(transactionIds);
				}
		});
	},
	
	// Create a function to process a single transaction at a time. This method prevents uncontrolled numbers of HTTP connections.
	_processOneTransaction: function (transactionIds) {
		var myself = this;
		if (transactionIds.length <= 0) {
			return;
		}
		var oneTransactionId = transactionIds.pop();
		Bank.Debit.getTransaction(oneTransactionId,
			function(error, tx) {
				myself._walkForward(error, tx, transactionIds);
		});
	},
	
	// Provide a means of processing a transaction in different states.
	_walkForward: function(error, tx, transactionIds) {
		var myself = this;
		//console.log("TXN: " + JSON.stringify(tx));
		if (error || (!error && !tx) || (!error && !tx && !tx.state)) {
			var errorCode = error.errorCode;
			var errorDesc = error.description;
			console.log('Error while processing transaction, Error: ' + errorCode + ', ' + errorDesc);
			myself._processOneTransaction(transactionIds);
		}
		else if (tx.state.toUpperCase() == 'NEW') {
			//console.log("Inside NEW");
			// When a tx is in the "new" state, you can call either continueTransaction() or cancelTransaction();
			Bank.Debit.cancelTransaction(tx.id,
				function(error,transaction){
					myself._processOneTransaction(transactionIds);
				});
		}
		else if (tx.state.toUpperCase() == 'AUTHORIZED') {
			//console.log("Inside AUTHORIZED");
			/* When a tx is in the "authorized" state,
			 * inventory is available funds are in escrow, and the user wants to move forward with the transaction.
			 * You can call openTransaction() or cancelTransaction().
			 */
			Bank.Debit.openTransaction(tx.id,
				function(error,transaction){
					if (error || (!error && !transaction) || (!error && !transaction && !transaction.state)) {
						var errorCode = error.errorCode;
						var errorDesc = error.description;
						console.log('Error while processing transaction, Error: ' + errorCode + ', ' + errorDesc);
						myself._processOneTransaction(transactionIds);
					}
					else {
						if (GAInAppPurchaseHandler.hasBeenCompleted(tx.id) == false) {
							myself._awardCurrency(myself.extractItemId(transaction.item.sku));
							GAInAppPurchaseHandler.addToCompletedTransactions(transaction.id);
						}
						Bank.Debit.closeTransaction(tx.id,
							function(error, transaction) {
								// Game-specific logic here
								myself._processOneTransaction(transactionIds);
						});
					}
				});
		}
		else if (tx.state == 'OPEN') {
			//console.log("Inside OPEN");
			/* When a tx is in the "open" state, you must ensure that the ordered items were delivered, 
			 * or that you deliver the items. You may call closeTransaction() or cancelTransaction.
			 * WARNING DO NOT CALL closeTransaction() if you have not delivered the item to the game client! 
			 */
			 if (GAInAppPurchaseHandler.hasBeenCompleted(tx.id) == true){
				Bank.Debit.closeTransaction(tx.id,
					function(error, transaction) {
					// Game-specific logic here
					myself._processOneTransaction(transactionIds);
				});
			}
			else {
				this._awardCurrency(myself.extractItemId(tx.item.sku));
				GAInAppPurchaseHandler.addToCompletedTransactions(tx.id);
				Bank.Debit.closeTransaction(tx.id,
					function(error, transaction) {
						// Game-specific logic here
						myself._processOneTransaction(transactionIds);
				});
			}
		}
		else {
			// Game-specific logic here for unknown state, this is unlikely
			console.log("GAInAppPurchaseHandler.synchPendingTransaction: Transaction is in unknown state");
			myself._processOneTransaction(transactionIds);
		}
	},

	extractItemId: function(sku) {
		if (sku != null) {
			// sku is in the form "debit:mallbucks_22"
			return sku.replace("debit:", "");
		}
		return null;
	}
	
});